/**
 * Created by Administrator on 2016/9/18.
 */
define(function (require, exports) {
    var ajaxUtil = require('util/ajaxUtil').ajaxUtil;
    var logUtil = require('util/logUtil').logUtil;
    var commonUtil = require('util/commonUtil').commonUtil;

    var controls = {};
    controls.app_user_mgr_detail_panel = $('#app_user_mgr_detail_panel');
    controls.app_user_mgr_list_panel = $('#app_user_mgr_list_panel');

    var urls = {};
    urls.list = '/admin/user/app-user-list';
    urls.disabled = '/admin/user/app-user-disabled';

    urls.app_user_save = '/admin/user/app-user-save';

    urls.order_list = '/admin/order/order-list';
    urls.video_list = '/admin/userVideo/list';
    urls.storage_list = '/admin/userStorage/list';

    var G_MODIFY = false;
    var G_CURRENT_DATA = null;
    
    var G_IS_LOAD_ORDER = false;
    var G_IS_LOAD_VIDEO = false;
    var G_IS_LOAD_STORAGE = false;

    function init() {
        bindEvent();
        loadModelData();
    }

    function showUserList() {
        controls.app_user_mgr_detail_panel.hide();
        controls.app_user_mgr_list_panel.show();
    }

    function showUserDetial() {
        controls.app_user_mgr_detail_panel.show();
        controls.app_user_mgr_list_panel.hide();
    }
    

    function bindEvent() {
        controls.app_user_mgr_list_panel.find('button:eq(0)').bind('click', function () {
            refresh();
        });

        controls.app_user_mgr_detail_panel.find('button:eq(0)').bind('click', function () {
            showUserList();
            refresh();
        });

        controls.app_user_mgr_detail_panel.find('button:eq(1)').bind('click', function () {
            bootbox.confirm({
                title: "温馨提示",
                message: "此过程不可逆，确认设置？",
                buttons: {
                    cancel: {
                        label: '<i class="fa fa-times"></i> 取消'
                    },
                    confirm: {
                        label: '<i class="fa fa-check"></i> 确认'
                    }
                },
                callback: function (result) {
                    if (result) {
                        var args = {};
                        args.id = G_CURRENT_DATA.id;
                        args.dev_tag = 1;
                        ajaxUtil.doAjaxPost(urls.app_user_save, args).done(function (ret) {
                            if (ret.status == 0) {
                                commonUtil.toast('设置成功')
                            } else {
                                commonUtil.toast(ret.msg);
                            }

                        });
                    }
                }
            });
        });


        $("#app_user_mgr_list_grid").on({
            'click': function () {
                var data = JSON.parse(decodeURIComponent($(this).data('user')));

                G_MODIFY = true;
                G_CURRENT_DATA = data;

                showUserDetial();

                let cxt = data.name||data.account;

                if (data.type === 0) {

                } else if (data.type === 1) {
                    cxt =  (data.name||data.account + '(月会员)');
                } else if (data.type === 2) {
                    cxt = (data.name||data.account + '(年会员)');
                } else {

                }

                controls.app_user_mgr_detail_panel.find('span:eq(0)').text(cxt||'');
                controls.app_user_mgr_detail_panel.find('span:eq(1)').text(data.account||'');
                controls.app_user_mgr_detail_panel.find('span:eq(2)').text(String(data.mobile)|'');
                controls.app_user_mgr_detail_panel.find('span:eq(3)').text(data.wechat||'');
                controls.app_user_mgr_detail_panel.find('span:eq(4)').text(data.qq|| '');
                controls.app_user_mgr_detail_panel.find('span:eq(5)').text(data.email||'');


                loadOrderData({user_id:data.id});
                loadVideoData({user_id:data.id});
                loadStorageData({user_id:data.id});

            }
        }, '.resource-modify');

        // 点击删除
        $("#app_user_mgr_list_grid").on({
            'click': function () {
                var data = JSON.parse(decodeURIComponent($(this).data('user')));

                var title = data.is_disable==0?'禁用':'启用';

                bootbox.confirm({
                    title: "温馨提示",
                    message: "确认"+title+"？",
                    buttons: {
                        cancel: {
                            label: '<i class="fa fa-times"></i> 取消'
                        },
                        confirm: {
                            label: '<i class="fa fa-check"></i> 确认'
                        }
                    },
                    callback: function (result) {
                        if (result) {
                            var args = {};
                            args.id = data.id;
                            args.status = data.is_disable==0?1:0;
                            ajaxUtil.doAjaxGet(urls.disabled, args).done(function (ret) {
                                if (ret.status == 0) {
                                    refresh();
                                } else {
                                    commonUtil.toast(ret.msg);
                                }

                            });
                        }
                    }
                });
            }
        }, '.resource-delete');
    }

    function refresh(data) {
        data = data || {};

        data.keyword = $.trim(controls.app_user_mgr_list_panel.find('input[type=text]:eq(0)').val());

        var page = $("#app_user_mgr_list_grid").getGridParam('page'); // current page
        var rows = $("#app_user_mgr_list_grid").getGridParam('rows'); // rows
        $("#app_user_mgr_list_grid").jqGrid('setGridParam', {
            postData: data,
            page: page,
            rows: rows
        }).trigger("reloadGrid")
    }

    function loadModelData() {
        $("#app_user_mgr_list_grid").jqGrid({
            colModel: [
                {
                    label: '用户名', name: 'account', align: 'center',
                    formatter: function (cellValue, options, rowObject) {
                        let cxt = cellValue;

                        if (rowObject.type === 0) {

                        } else if (rowObject.type === 1) {
                            cxt =  (cellValue + '(月会员)');
                        } else if (rowObject.type === 2) {
                            cxt = (cellValue + '(年会员)');
                        } else {

                        }

                        return '<a data-user="' + encodeURIComponent(JSON.stringify(rowObject)) + '" href="javascript:;" class="resource-modify" style="color: #01AAED;">'+cxt+'</a>&nbsp;&nbsp;'
                    }
                },
                {label: '用户名称', name: 'name', align: 'center'},
                {label: '电子邮件', name: 'email', align: 'center'},
                {label: '联系电话', name: 'mobile', align: 'center'},
                {
                    label: '消费金额', name: 'total_payment', align: 'center',
                    formatter: function (cellValue, options, rowObject) {
                        if (cellValue) {
                            return '¥' + cellValue
                        } else {
                            return '-'
                        }
                    }
                },
                {
                    label: '存储容量', name: 'storage', align: 'center',
                    formatter: function (cellValue, options, rowObject) {
                        let storage = Math.floor(cellValue / (1024 * 1024));

                        if (Math.floor(storage / (1024)) >= 1) {
                            return ((storage / 1024).toFixed(0)) + 'G'
                        } else {
                            return (cellValue / (1024 * 1024)).toFixed(0) + 'M'
                        }

                    }
                },
                {
                    label: '会员到期时间',
                    name: 'over_time',
                    align: 'center',
                    formatter: function (cellValue, options, rowObject) {
                        if (rowObject.type === 0) {
                            return ('-');
                        } else {
                            return commonUtil.getTimeString(cellValue);
                        }

                    }
                },
                {
                    label: '操作', align: 'center',
                    formatter: function (cellValue, options, rowObject) {
                        return  '<a data-user="' + encodeURIComponent(JSON.stringify(rowObject)) + '" href="javascript:;" class="resource-delete" style="color: #01AAED;">'+(rowObject.is_disable==0?"禁用":"启用")+'</a>'
                    }
                }
            ],
            styleUI: 'Bootstrap',
            datatype: 'json',
            url: urls.list,
            rowNum: 10,
            rowList: [10, 20, 30],
            viewrecords: true, // show the current page, data rang and total records on the toolbar
            height: true,
            fitColumns: true,
            width: true,
            autowidth: true,
            shrinkToFit: true,
            ajaxGridOptions: {
                dataFilter: function (ret) {
                    var retObj = JSON.parse(ret);
                    if (retObj.status == 0) {
                        return JSON.stringify(retObj.data);
                    } else {
                        commonUtil.toast(retObj.msg);
                    }
                }
            },
            pager: "#app_user_mgr_list_grid_pager"
        });
        // 初始化宽宽，用于自适应宽度
        $("#app_user_mgr_list_grid").setGridWidth($("#page-wrapper").width(), true);
    }
    
    function loadOrderData(data) {
        data = data || {};
        
        if(!G_IS_LOAD_ORDER) {
            $("#app_user_order_mgr_list_grid").jqGrid({
                colModel: [
                    {label: '订单号', name: 'flow_no', align: 'center'},
                    {label: '用户名', name: 'user_id', align: 'center'},
                    {label: '订单内容', name: 'body', align: 'center'},
                    {
                        label: '下单时间',
                        name: 'create_time',
                        align: 'center',
                        formatter: function (cellValue, options, rowObject) {
                            return commonUtil.getTimeString(cellValue);
                        }
                    },
                    {label: '支付状态', name: 'status', align: 'center'},
                    {label: '金额', name: 'payment', align: 'center'},
                    {label: '备注', name: 'remark', align: 'center'},
                    {
                        label: '操作', align: 'center',
                        formatter: function (cellValue, options, rowObject) {
                            return  '<a data-user="' + encodeURIComponent(JSON.stringify(rowObject)) + '" href="javascript:;" class="resource-delete" style="color: #01AAED;">修改金额</a>'
                        }
                    }
                ],
                styleUI: 'Bootstrap',
                datatype: 'json',
                url: urls.order_list,
                rowNum: 10,
                rowList: [10, 20, 30],
                viewrecords: true, // show the current page, data rang and total records on the toolbar
                height: true,
                fitColumns: true,
                width: true,
                autowidth: true,
                postData: data,
                shrinkToFit: true,
                ajaxGridOptions: {
                    dataFilter: function (ret) {
                        var retObj = JSON.parse(ret);
                        if (retObj.status == 0) {
                            return JSON.stringify(retObj.data);
                        } else {
                            commonUtil.toast(retObj.msg);
                        }
                    }
                },
                pager: "#app_user_order_mgr_list_grid_pager"
            });
            // 初始化宽宽，用于自适应宽度
            $("#app_user_order_mgr_list_grid").setGridWidth($("#page-wrapper").width(), true);
            
            G_IS_LOAD_ORDER = true;
        } else {

            var page = $("#app_user_order_mgr_list_grid").getGridParam('page'); // current page
            var rows = $("#app_user_order_mgr_list_grid").getGridParam('rows'); // rows
            $("#app_user_order_mgr_list_grid").jqGrid('setGridParam', {
                postData: data,
                page: page,
                rows: rows
            }).trigger("reloadGrid")
        }
    }

    function loadStorageData(data) {
        data = data || {};
        if(!G_IS_LOAD_STORAGE){
            $("#app_user_storage_mgr_list_grid").jqGrid({
                colModel: [
                    {
                        label: '用户名', name: 'user_id', align: 'center',
                        formatter: function (cellValue, options, rowObject) {
                            return (rowObject.app_user||'')&&rowObject.app_user.account;
                        }
                    },
                    { label: '类型', name: 'type', align: 'center'},
                    { label: '文件名', name: 'file_name', align: 'center'},
                    { label: '下载地址', name: 'remote_url', align: 'center',
                        formatter: function (cellValue, options, rowObject) {
                            return '<a href="' +rowObject.remote_url+ '" target="_blank">' +rowObject.remote_url+ '</a>';
                        }
                    },
                    {
                        label: '创建时间',
                        name: 'create_time',
                        align: 'center',
                        formatter: function (cellValue, options, rowObject) {
                            return commonUtil.getTimeString(cellValue);
                        }
                    },
                    {
                        label: '操作', align: 'center',
                        formatter: function (cellValue, options, rowObject) {
                            return '-'
                        }
                    }
                ],
                styleUI: 'Bootstrap',
                datatype: 'json',
                url: urls.storage_list,
                rowNum: 10,
                postData: data,
                rowList: [10, 20, 30],
                viewrecords: true, // show the current page, data rang and total records on the toolbar
                height: true,
                fitColumns: true,
                width: true,
                autowidth: true,
                shrinkToFit: true,
                ajaxGridOptions: {
                    dataFilter: function (ret) {
                        var retObj = JSON.parse(ret);
                        if (retObj.status == 0) {
                            return JSON.stringify(retObj.data);
                        } else {
                            commonUtil.toast(retObj.msg);
                        }
                    }
                },
                pager: "#app_user_storage_mgr_list_grid_pager"
            });
            // 初始化宽宽，用于自适应宽度
            $("#app_user_storage_mgr_list_grid").setGridWidth($("#page-wrapper").width(), true);
            
            G_IS_LOAD_STORAGE = true;
        } else {

            var page = $("#app_user_storage_mgr_list_grid").getGridParam('page'); // current page
            var rows = $("#app_user_storage_mgr_list_grid").getGridParam('rows'); // rows
            $("#app_user_storage_mgr_list_grid").jqGrid('setGridParam', {
                postData: data,
                page: page,
                rows: rows
            }).trigger("reloadGrid")
        }
    }
    
    function loadVideoData(data) {
        data = data || {};
        
        if(!G_IS_LOAD_VIDEO) {
            $("#app_user_video_mgr_list_grid").jqGrid({
                colModel: [
                    {
                        label: '用户名', name: 'user_id', align: 'center',
                        formatter: function (cellValue, options, rowObject) {
                            return (rowObject.app_user||'')&&rowObject.app_user.account;
                        }
                    },
                    {
                        label: '标题',
                        name: 'template_id',
                        align: 'center',
                        formatter: function (cellValue, options, rowObject) {
                            var linkText = (rowObject.app_template||'')&&rowObject.app_template.title;
                            return '<a href="' +rowObject.download_url+ '" target="_blank">' +linkText+ '</a>';
                        }
                    },
                    {
                        label: '创建时间',
                        name: 'create_time',
                        align: 'center',
                        formatter: function (cellValue, options, rowObject) {
                            return commonUtil.getTimeString(cellValue);
                        }
                    },
                    {
                        label: '操作', align: 'center',
                        formatter: function (cellValue, options, rowObject) {
                            return '-'
                        }
                    }
                ],
                styleUI: 'Bootstrap',
                datatype: 'json',
                url: urls.video_list,
                rowNum: 10,
                rowList: [10, 20, 30],
                viewrecords: true, // show the current page, data rang and total records on the toolbar
                height: true,
                fitColumns: true,
                width: true,
                autowidth: true,
                shrinkToFit: true,
                ajaxGridOptions: {
                    dataFilter: function (ret) {
                        var retObj = JSON.parse(ret);
                        if (retObj.status == 0) {
                            return JSON.stringify(retObj.data);
                        } else {
                            commonUtil.toast(retObj.msg);
                        }
                    }
                },
                pager: "#app_user_video_mgr_list_grid_pager"
            });
            // 初始化宽宽，用于自适应宽度
            $("#app_user_video_mgr_list_grid").setGridWidth($("#page-wrapper").width(), true);
            
            G_IS_LOAD_VIDEO = true;
        }
        else {
            var page = $("#app_user_video_mgr_list_grid").getGridParam('page'); // current page
            var rows = $("#app_user_video_mgr_list_grid").getGridParam('rows'); // rows
            $("#app_user_video_mgr_list_grid").jqGrid('setGridParam', {
                postData: data,
                page: page,
                rows: rows
            }).trigger("reloadGrid")
        }
    }

    exports.init = init;
});